import {
  getPage
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  $empty,
  $toast,
  storage,
  Validate
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressForm: {
      name: '',
      price: '',
      orderamount: '',
      num: '',
      litmitnum: '',
      starttime: '',
      endtime: '',
    },
    currentDate: new Date(2024, 0, 1).getTime(),
    minDate: new Date(1950, 12).getTime(),
    maxDate: new Date(2030, 11).getTime(),
  },
  
  nameInput(e) {
    this.setData({
      nameInputError: '',
      'addressForm.name': e.detail,
    });
  },
  priceInput(e) {
    this.setData({
      priceError: '',
      "addressForm.price": $empty(e.detail)
    })
  },
  orderamountInput(e) {
    this.setData({
      orderamountError: '',
      "addressForm.orderamount": $empty(e.detail)
    })
  },
  numInput(e) {
    this.setData({
      numError: '',
      "addressForm.num": $empty(e.detail)
    })
  },
  litmitnumInput(e) {
    this.setData({
      litmitnumError: '',
      "addressForm.litmitnum": $empty(e.detail)
    })
  },

  toggle(type) {
    this.setData({
      [type]: !this.data[type]
    });
  },

  starttimeInput() {
    this.toggle('showstarttime')
  },
  endtimeInput() {
    this.toggle('showendtime')
  },

  //确定开始时间
  handleConfirmDateSta(e) {
    const {
      detail
    } = e;
    this.setData({
      "addressForm.starttime": this.dateFormat(detail)
    })
    this.starttimeInput();
  },
  //确定结束时间
  handleConfirmDateEnd(e) {
    const {
      detail
    } = e;
    this.setData({
      "addressForm.endtime": this.dateFormat(detail)
    })
    this.endtimeInput();
  },

  //时间格式化
  dateFormat(timestamp) {
    console.log(timestamp);
    if (timestamp != void 0) {
      let time = new Date(timestamp);
      let y = time.getFullYear();
      let M = time.getMonth() + 1;
      let d = time.getDate() ;
      let res_m = M<10?'0'+M:M;
      let res_d = d<10?'0'+d:d;

      return y + '-' + res_m + '-' + res_d
    }
  },
  
  /**
   * 提交保存
   */
  couponForm(e) {
    Validate.check(this, this.expressValidate, e.detail.value, (res) => {
      if (res) {
        const data = this.data;
        const {
          shopid,
          userId
        } = this.data;
        const {
          name,
          price,
          orderamount,
          num,
          litmitnum,
          starttime,
          endtime
        } = data.addressForm;
        const params = {
          action: 'addcoupon',
          name: name,
          price: price,
          orderamount: orderamount,
          num: num,
          litmitnum: litmitnum,
          starttime: starttime,
          endtime: endtime,
          shopid: shopid
        }
        console.log('params===',params)
        http.post(api.default, {
          data: params
        }).then((res) => {
          if (res.data.code == 0) {
            $toast('保存成功', {
              icon: 'success'
            });
            const pages = getCurrentPages()[getCurrentPages().length - 2];

            wx.navigateBack({
              delta: 1,
              success() {
                if (pages !== undefined || pages !== null) {
                  pages.data.pageChange = 1;
                  pages.onLoad();
                }
              }
            });
          } else {
            $toast(res.data.errmsg, {
              icon: 'fail'
            });
          }
        });
      } else {
        $toast("请确认信息填写完成！");
      }
    });

  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    app.getLogin().then((res) => {
      this.setData({
        userInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop.ShopId
      });
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    });
    
    if (JSON.stringify(options) !== '{}') {
      // this.setData({
      //   id: options.id
      // });
      // http.post(api.default, {
      //   data: {
      //     action: 'getcaseinfo',
      //     id: options.id
      //   }
      // }).then((res) => {
      //   const data = res.data.data;
      //   this.setData({
      //     'addressForm.name': data.info.name,
      //     'addressForm.price': data.info.price,
      //     'addressForm.orderamount': data.info.orderamount,
      //     'addressForm.num': data.info.num,
      //     'addressForm.litmitnum': data.info.litmitnum,
      //     'addressForm.starttime': data.info.starttime,
      //     'addressForm.endtime': data.info.endtime,
      //   });
      // });
    }
    //获取验证规则
    Validate.rules('#name,#price,#orderamount,#num,#litmitnum,#starttime,#endtime', (res) => {
      this.expressValidate = res;
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },



  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})